package com.example.shop.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.shop.controller.converter.ShopDataConverter;
import com.example.shop.entity.QueryResponse;
import com.example.shop.entity.Shop;
import com.example.shop.service.AuthService;
import com.example.shop.service.ShopService;
import com.example.shop.utils.Base64Util;
import com.example.shop.utils.CommonUtils;
import com.example.shop.utils.HttpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
public class PictureController {

    @Autowired
    private AuthService authService;

    @Autowired
    private ShopService shopService;

    @Autowired
    private ShopDataConverter dataConverter;


    /**
     * 相似图查询匹配
     *
     * @param file
     * @return
     */
    @PostMapping("/api/picture/query/{score}")
    public Map<String, Object> multiObjectDetect(@RequestParam("file") MultipartFile file, @PathVariable(value = "score") String score) {
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/realtime_search/similar/search";
        try {
            String imgStr = Base64Util.encode(file.getBytes());
            String imgParam = URLEncoder.encode(imgStr, "UTF-8");
            String param = "image=" + imgParam;
            //+ "&pn=" + 0 + "&rn=" + 100; // + "&tags=" + "1,2" + "&tag_logic=" + 1;
            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
            String accessToken = authService.getAuth();
            String result = HttpUtil.post(url, accessToken, param);

            Object obj = JSONObject.parse(result);
            Map<String, Object> map = CommonUtils.convertToMap(obj);
            List<QueryResponse> queryResponseList = JSONArray.parseArray(map.get("result").toString(), QueryResponse.class);
            List<QueryResponse> filterResponse = queryResponseList.stream().filter(e ->
                    e.getScore() >= Double.parseDouble(score)
            ).collect(Collectors.toList());
            List<String> contSignList = filterResponse.stream().map(QueryResponse::getCont_sign).collect(Collectors.toList());
            List<Shop> shopList = new ArrayList<>();
            if (!contSignList.isEmpty()) {
                shopList = shopService.search(contSignList);
            }
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("result", shopList.stream().map(dataConverter::to).collect(Collectors.toList()));
            resultMap.put("shopImg", imgParam);
            resultMap.put("shopName", file.getOriginalFilename());
            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 图片入库
     *
     * @param file
     * @return
     */
    @PostMapping("/picture/add")
    public String similarAdd(@RequestParam("file") MultipartFile file) {
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/realtime_search/similar/add";
        try {
            String imgStr = Base64Util.encode(file.getBytes());
            String imgParam = URLEncoder.encode(imgStr, "UTF-8");
            String param = "brief=" + file.getOriginalFilename() + "&image=" + imgParam + "&tags=" + "1,2";
            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
            String accessToken = authService.getAuth();
            String result = HttpUtil.post(url, accessToken, param);

            Object obj = JSONObject.parse(result);
            Map<String, Object> map = CommonUtils.convertToMap(obj);
            String cont_sign = map.get("cont_sign").toString();
            // 本地存数据
            Shop shop = new Shop();
            shop.setName(file.getOriginalFilename());
            shop.setContSign(cont_sign);
            String base64 = "data:image/jpeg;base64," + imgParam;
            shop.setImage(base64);
            shopService.insert(shop);

            return cont_sign;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


}
